﻿"""
Definition of views.
"""

from django.shortcuts import render
from django.http import HttpRequest,HttpResponse,HttpResponseRedirect,JsonResponse
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.utils import timezone
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.conf import settings
from django.core.mail import send_mass_mail
from django.core.mail import send_mail
from django.http import StreamingHttpResponse 

from .models import Message
from .models import Vacation
from .models import User

from django.template import RequestContext
from datetime import datetime
from django.contrib.auth.hashers import make_password, check_password
from django.db.models import Sum
import json
import sys

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)  
    sys.setdefaultencoding(default_encoding)

def user(request):
    #context={"messages":Message.objects.order_by('-publish_date')}
    #return render(request,'online/user.html')
    username=request.session.get('username')
    if username :
      return render(request,'online/user.html')
    else :
      return render(request,'online/login.html')

@csrf_exempt
def saveuser(request):
  uname = request.POST.get('username','')
  upwd = request.POST.get('userpwd','')
  umail = request.POST.get('usermail','')
  uresume = request.POST.get('userresume','')
  entdate = request.POST.get('entrydate','')
  udept = request.POST.get('udept','')
  utype =0 #0 general user 1 admin user
  uregdate =timezone.now()
  temps=request.POST.get('temp','')
  remarks =''
  
  if uname and upwd and umail and entdate:
   upwdjm=make_password(upwd, 'mao', 'pbkdf2_sha256')
   #upwdjm=make_password(upwd, None, 'pbkdf2_sha256')
   obj = User(username=uname,useremail=umail,usertype=utype,userdepartment=udept,userpwd=upwdjm,userresume=uresume,regdate=uregdate,entrydate=entdate,temp=temps,remark=remarks)
   obj.save()
   #dj_ps = make_password(ps, None, 'pbkdf2_sha256')   #创建django密码， 第二个参数为None是每次产生的密码都不用，第三个参数为算法， 后面两个参数可以忽略
   #ps_bool = check_password(ps, dj_ps) # check_password 返回值为一个Bool类型，验证密码的正确与否
   context={'success':'1','error':'0'}
   return HttpResponse(json.dumps(context), content_type='application/json')
  else :
     context={'success':'0','error':'1'}
     return JsonResponse(context)

@csrf_exempt
def deluser(request):
  ids = request.POST.get('id','')
  if id:
   User.objects.filter(id=ids).delete()
   context={'success':'1','error':'0'}
   return HttpResponse(json.dumps(context), content_type='application/json')
  else :
     context={'success':'0','error':'1'}
     return JsonResponse(context)

@csrf_exempt
def edituser(request):
  ids = request.POST.get('id','')

  uname = request.POST.get('username','')
  upwd = request.POST.get('userpwd','')
  umail = request.POST.get('usermail','')
  uresume = request.POST.get('userresume','')
  entdate = request.POST.get('entrydate','')
  udept = request.POST.get('udept','')
  utype =0 #0 general user 1 admin user
  uregdate =timezone.now()
  temps=request.POST.get('temp','')
  remarks =''

  if ids:
   upwdjm=make_password(upwd,'mao', 'pbkdf2_sha256')
   #upwdjm=make_password(upwd, None, 'pbkdf2_sha256')
   User.objects.filter(id=ids).update(username=uname,useremail=umail,usertype=utype,userdepartment=udept,userpwd=upwdjm,userresume=uresume,regdate=uregdate,entrydate=entdate,temp=temps,remark=remarks)
   context={'success':'1','error':'0'}
   return HttpResponse(json.dumps(context), content_type='application/json')
  else :
     context={'success':'0','error':'1'}
     return JsonResponse(context)

@csrf_exempt
def userlogin(request):
  uname = request.POST.get('username','')
  upwd = request.POST.get('userpwd','')
  if uname and upwd:
   data_set = []
   #user=len(User.objects.filter(useremail=uname,userpwd=pwdjm))
   #user=User.objects.filter(username=uname,userpwd=upwd)
   #"id":asset["id"],"username":asset["username"],"useremail":asset["useremail"],"usertype":asset["usertype"],"userdepartment":asset["userdepartment"],"userpwd":asset["userpwd"],"userresume":asset["userresume"],"regdate":asset["regdate"],"entrydate":asset["entrydate"],"temp":asset["temp"],"remark":asset["remark"]
   upwdjm=make_password(upwd,'mao', 'pbkdf2_sha256')
   user=User.objects.filter(useremail=uname,userpwd=upwdjm)
   if user and user[0]:
          request.session['userdepartment']=user[0].userdepartment
          request.session['username']=user[0].username
          request.session['useremail']=user[0].useremail
          context={'success':'1','error':'0'}
          #context={'success':'1','error':'0',"id":user[0].id,"username":user[0].username}
          return JsonResponse(context)
   else:
          context={'success':'0','error':'1'}
          return JsonResponse(context)

@csrf_exempt
def username(request):
  username=request.session.get('username')
  userdep=request.session.get('userdepartment')
  admins=0
  if int(userdep)==settings.ADMIN_USER_ID :
    admins=1
  if username:
       context={'success':'1','error':'0','uname':username,'admin':admins}
       #context={'success':'1','error':'0',"id":user[0].id,"username":user[0].username}
       return JsonResponse(context)
  else:
       context={'success':'0','error':'1'}
       return JsonResponse(context)
@csrf_exempt
def userlogout(request):
    try:
     del request.session['userdepartment']
     del request.session['username']
     del request.session['useremail']
     context={'success':'1','error':'0'}
     return JsonResponse(context)
    except Exception:
       context={'success':'0','error':'1'}
       return JsonResponse(context)

@csrf_exempt
def upload_ajax(request):
    if request.method == 'POST':
        file_obj = request.FILES.get('file')
        import os
        time = timezone.localtime(timezone.now()).strftime("%Y%m%d%H%M%S")
        time=time+os.path.splitext(file_obj.name)[1]
        f = open(os.path.join(settings.BASE_DIR, 'online', 'doc',time),'wb')
        for chunk in file_obj.chunks():
            f.write(chunk)
        f.close()
        context={'success':'1','error':'0','newfilename':time}
        return JsonResponse(context)
def file_download(request):
    file_obj = request.GET.get('filename')
    with open(settings.BASE_DIR+'/online/doc/'+file_obj,encoding='gb18030', errors='ignore') as f:
        c = f.read()
    return HttpResponse(c)

def file_down(request):
    file_obj = request.GET.get('filename')
    file=open(settings.BASE_DIR+'/online/doc/'+file_obj,'rb')  
    response =HttpResponse(file)  
    response['Content-Type']='application/octet-stream'  
    response['Content-Disposition']='attachment;filename='+file_obj
    return response

def list(request):
    json_data = serializers.serialize("json", Message.objects.all(),ensure_ascii = False)
    return HttpResponse(json_data,content_type="application/json")
 
def getuserlist(request):
    userlist=settings.USER_LIST
    return HttpResponse(json.dumps(userlist),content_type='application/json')

def page(deploy_list ,limit,offset):
    try:
        paginator = Paginator(deploy_list, limit)
    except Exception:
        return {"data":'none',"response_data":'none'}
    page = int(int(offset) / int(limit) + 1)
    data=paginator.page(page)
    response_data = {'total': deploy_list.count(), 'rows': []}
    return {"data":data,"response_data":response_data}

def listuser(request):
    data_set = []
    userdep=request.session.get('userdepartment')
    if userdep and int(userdep)==settings.ADMIN_USER_ID:
      length = len(User.objects.all())
      paginator = Paginator(User.objects.all().order_by("-id").values(), 100)
      page = int(int(0) / int(1) + 1)
      data=paginator.page(page)
      for asset in data:
        data_set.append({ "id":asset["id"],"username":asset["username"],"useremail":asset["useremail"],"usertype":asset["usertype"],"userdepartment":asset["userdepartment"],"userpwd":asset["userpwd"],"userresume":asset["userresume"],"regdate":asset["regdate"],"entrydate":asset["entrydate"],"temp":asset["temp"],"remark":asset["remark"]})
      return HttpResponse(json.dumps({'rows':data_set,'total':length}),content_type='application/json')
    else :
        return HttpResponse(json.dumps({'rows':-1,'total':-1,'role':-1}),content_type='application/json')
    #return  HttpResponse(json.dumps(J_data["response_data"]))

    #for asset in Vacation.objects.all().values():

    #data_set.append(asset.getAttrs())
#J_data['response_data']['model'].append({ "vac_date":asset["vac_date"],"vac_person":asset["vac_person"],"vac_interval":asset["vac_interval"],"vac_reason":asset["vac_reason"],"vac_enddate":asset["vac_enddate"],"vac_temp":asset["vac_temp"]})

#J_data=page(Vacation.objects.all().values(),request.GET.get("limit"),request.GET.get("offset"))

    #resp = {'errorcode': 100, 'detail': 'Get success'}
    #return HttpResponse(json.dumps(resp), content_type="application/json")
	
	#data = models.Message.objects.values('username', 'title', 'contents', 'publish_date')
    #data = serializers.serialize("json", tomcats)
    #return JsonResponse(list(data), safe=False)